<?php

namespace addons\aliyunemail\library;

use addons\aliyunemail\library\sdk\Client;
use addons\aliyunemail\library\sdk\ClientNew;

class Aliyunemail
{
    private $_params = [];
    protected $error = '';
    protected $config = [];
    protected static $instance = null;

    public function __construct($options = [])
    {
        if ($config = get_addon_config('aliyunemail')) {
            $this->config = array_merge($this->config, $config);
        }
        $this->config = array_merge($this->config, is_array($options) ? $options : []);
    }

    /**
     * 单例
     * @param array $options 参数
     * @return Aliyunemail
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    /**
     * 立即发送邮件
     *
     * @return boolean
     */
    public function send()
    {
        $this->error = '';
        $params = $this->_params();
        
        try {
            // 构建endpoint
            $endpoint = 'dm.' . $this->config['region'] . '.aliyuncs.com';
            
            // 创建客户端
            $client = new ClientNew(
                $this->config['access_key_id'],
                $this->config['access_key_secret'],
            );

            // Determine if it is a verification code email or a notification email
            $subject = 'Verification Code Email';
            $htmlBody = '';
            $textBody = '';

            // If it is a verification code email, extract the code
            if (isset($params['code'])) {
                $subject = 'Your Verification Code';
                $htmlBody = $this->buildVerificationCodeHtml($params['code']);
                $textBody = "Your verification code is: {$params['code']}. Please use it within 5 minutes.";
            } else {
                // Notification email
                $subject = 'System Notification';
                $htmlBody = $this->buildNoticeHtml($params['msg']);
                $textBody = $params['msg'];
            }

            // dump('111111');
            // dump($this->config);

            // exit;

            // 发送邮件
            $result = $client->sendMail(
                $this->config['from_address'],
                $params['email'],
                $subject,
                $htmlBody,
                $this->config['from_alias'],
                $textBody
            );

            // 检查结果
            if (isset($result['RequestId'])) {
                return true;
            } else {
                $this->error = isset($result['Message']) ? $result['Message'] : '发送失败';
                return false;
            }

        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 构建验证码HTML邮件内容
     * @param string $code
     * @return string
     */
    private function buildVerificationCodeHtml($code)
    {
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='utf-8'>
            <title>Verification Code Email</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #f8f9fa; padding: 20px; text-align: center; border-radius: 5px; }
                .content { padding: 20px; background: #fff; }
                .code { font-size: 24px; font-weight: bold; color: #007bff; text-align: center; padding: 20px; background: #f8f9fa; border-radius: 5px; margin: 20px 0; }
                .footer { text-align: center; color: #666; font-size: 12px; margin-top: 20px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Verification Code Email</h2>
                </div>
                <div class='content'>
                    <p>Hello!</p>
                    <p>You are using the email verification feature. Your verification code is:</p>
                    <div class='code'>{$code}</div>
                    <p>Please use this verification code within 5 minutes. The code will expire after that.</p>
                    <p>If this was not your operation, please ignore this email.</p>
                </div>
                <div class='footer'>
                    <p>This email was sent automatically by the system. Please do not reply.</p>
                </div>
            </div>
        </body>
        </html>";
    }

    /**
     * 构建通知HTML邮件内容
     * @param string $message
     * @return string
     */
    private function buildNoticeHtml($message)
    {
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='utf-8'>
            <title>System Notification</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #f8f9fa; padding: 20px; text-align: center; border-radius: 5px; }
                .content { padding: 20px; background: #fff; }
                .footer { text-align: center; color: #666; font-size: 12px; margin-top: 20px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>System Notification</h2>
                </div>
                <div class='content'>
                    <p>Hello!</p>
                    <p>{$message}</p>
                </div>
                <div class='footer'>
                    <p>This email was sent automatically by the system. Please do not reply.</p>
                </div>
            </div>
        </body>
        </html>";
    }

    private function _params()
    {
        return array_merge([], $this->_params);
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 接收邮箱
     * @param   string $email 邮箱地址
     * @return Aliyunemail
     */
    public function email($email = '')
    {
        $this->_params['email'] = $email;
        return $this;
    }

    /**
     * 邮件内容
     * @param   string $msg 邮件内容
     * @return Aliyunemail
     */
    public function msg($msg = '')
    {
        // For Alibaba Cloud emails, the content is controlled by the template, mainly used for extracting verification codes
        if (preg_match('/Verification Code[is:：]\s*(\d+)/', $msg, $matches)) {
            $this->_params['code'] = $matches[1];
        } else {
            // Notification email, save the original content
            $this->_params['msg'] = $msg;
        }
        return $this;
    }
}
